#include "Channel.h"
#include "EventLoop.h"
#include "Logger.h"
#include <sys/epoll.h>

const int Channel::kNoneEvent = 0;
const int Channel::kReadEvent = EPOLLIN | EPOLLPRI;
const int Channel::kWriteEvent = EPOLLOUT;

Channel::Channel(EventLoop *loop, int fd)
    : loop_(loop), fd_(fd), events_(0), revents_(0), index_(-1), tied_(false)
{
    LOG_INFO("Channel fd=%d ctor", fd_);
}

Channel::~Channel()
{
    LOG_INFO("Channel fd=%d dtor", fd_);
}

// 新连接建立的时候，Channel要绑定一个TcpConnection
void Channel::tie(const std::shared_ptr<void> &obj)
{
    tie_ = obj;
    tied_ = true;
}

/**
 * 当channel中的fd的events_发生改变的时候，update负责poller里面更改fd相应的事件，通过epoll_ctl实现
 */
void Channel::update()
{
    // 通过channel所属的eventloop调用poller的相关方法，注册fd的events事件
    loop_->updateChannel(this);
}
void Channel::remove()
{
    // 在channel所属的eventloop中，删除当前channel
    loop_->removeChannel(this);
}
void Channel::handleEvent(Timestamp receiveTime)
{
    if (tied_)
    {
        std::shared_ptr<void> guard = tie_.lock();
        if (guard)
        {
            handleEventWithGuard(receiveTime);
        }
    }
    else
    {
        handleEventWithGuard(receiveTime);
    }
}
// 由poller通知channel发生的具体事件，channel来执行具体的回调操作
void Channel::handleEventWithGuard(Timestamp receiveTime)
{
    LOG_INFO("Channel::handleEventWithGuard revents:%d", revents_);

    if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN))
    {
        if (closeCallback_)
        {
            closeCallback_();
        }
    }
    if (revents_ & EPOLLERR)
    {
        if (errorCallback_)
        {
            errorCallback_();
        }
    }
    if (revents_ & (EPOLLIN | EPOLLPRI))
    {
        if (readCallback_)
        {
            readCallback_(receiveTime);
        }
    }
    if (revents_ & EPOLLOUT)
    {
        if (writeCallback_)
        {
            writeCallback_();
        }
    }
}
